package p2pcdnsim.network.example;

import p2pcdnsim.exception.PortAlreadyInUseException;
import p2pcdnsim.network.ApplicationProcess;
import p2pcdnsim.network.ServerSocket;
import p2pcdnsim.network.Socket;
import desmoj.core.simulator.Model;
import desmoj.core.simulator.SimTime;

public class ExampleServerProcess extends ApplicationProcess {

	public ExampleServerProcess(Model owner, String name) {
		super(owner, name);
	}

	@Override
	protected void run() {
		ServerSocket server = null;
		try {
			server = this.createServerSocket(80);
		} catch (PortAlreadyInUseException e) {
			throw new RuntimeException(e);
		}
		
		while(true) {
			System.out.println("["+this.currentTime()+"] Server: Waiting for a connection...");
			Socket socket = server.accept();
			//Create a process to handle the incoming connection
			ServerRoutine routine =  new ServerRoutine(this.getModel(),this.getName(),socket);
			routine.activate(new SimTime(0.0));
			System.out.println("["+this.currentTime()+"] Server: routine process created.");
		}
		
	
	}

	private class ServerRoutine extends ApplicationProcess {

		Socket socket;
		
		public ServerRoutine(Model owner, String name, Socket socket) {
			super(owner, name);
			this.socket = socket;
		}
		
		@Override
		protected void run() {
			System.out.println("["+this.currentTime()+"] ServerRoutine: Accepted a connection: "+socket);
	
		}
	}

}
